package com.glsc.ngateway.platform.service.cmdb;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbChangeLog;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbCpuDetail;
import com.glsc.ngateway.common.base.domain.mysql.cmdb.CmdbDeviceDetail;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.cmdb.FlowFormPartIn;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.CmdbChangeLogRepository;
import com.glsc.ngateway.common.base.repo.mysql.cmdb.CmdbCpuDetailRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.flow.cmdb.FlowFormPartInRepo;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.*;

@Service
public class CmdbCpuDetailService {

    @Autowired
    private SequenceProductService sequenceProductService;
    @Autowired
    private CmdbCpuDetailRepository cmdbCpuDetailRepository;
    @Autowired
    private CmdbChangeLogRepository cmdbChangeLogRepository;
    @Autowired
    private FlowFormPartInRepo flowFormPartInRepo;

    public Object search(String type, Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))) {
            objParmams.put("orderByDirection", "DESC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))) {
            objParmams.put("orderByField", "id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo") - 1, objParmams.getInteger("pageSize"), sort);

        if (CMDB_CPU_DETAIL.equals(type)) {
            CmdbCpuDetail paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(objParmams), CmdbCpuDetail.class);
            Page<CmdbCpuDetail> result = cmdbCpuDetailRepository.searchByParam(pageable, paramSearchDto);
            result.getContent().forEach(e -> {
                if (e.getCmdbCpuStandard() != null) {
                    e.setPartNum(e.getCmdbCpuStandard().getPartNum());
                }
            });
            return result;
        }

        return null;
    }

    /**
     * @param cmdbCpuDetail
     * @param account       操作人员
     * @param cmdbConfirm
     */
    public CmdbCpuDetail addOrUpdateCpuDetail(CmdbCpuDetail cmdbCpuDetail, String account, String cmdbConfirm) {
        int addOrUpdateFlag = 0;
        cmdbCpuDetail.setIsDelete(NO_DELETE);
        CmdbChangeLog log = new CmdbChangeLog();
        if (cmdbCpuDetail.getCpuDetailId() != null) {
            // 修改
            log.setChangeType(DictConstant.UPDATE_STRING);
            addOrUpdateFlag = 2;
        } else {
            // 新增
            log.setChangeType(DictConstant.ADD_STRING);
            // 自动生成编号
            String code = sequenceProductService.buildSequence(CMDB_CPU_DETAIL);
            cmdbCpuDetail.setCpuDetailCode(code);
            addOrUpdateFlag = 1;
        }
        //校验重复
        if (addOrUpdateFlag != 0){
            checkUnique(cmdbCpuDetail, addOrUpdateFlag,cmdbConfirm);
        }
        log.setChangeContent(JSONObject.toJSONString(cmdbCpuDetail));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeId(cmdbCpuDetail.getCpuDetailId() != null ? cmdbCpuDetail.getCpuDetailId().toString() : null);
        log.setChangeUser(account);
        cmdbChangeLogRepository.save(log);
        cmdbCpuDetailRepository.save(cmdbCpuDetail);
        return cmdbCpuDetail;
    }

    private void checkUnique(CmdbCpuDetail cmdbCpuDetail, int addOrUpdateFlag, String cmdbConfirm) {
        if (StrUtil.isNotEmpty(cmdbCpuDetail.getSn())) {
            if (addOrUpdateFlag == 1) {
                findSame(cmdbCpuDetail,cmdbConfirm);
            } else {
                //修改情况，要把已有结果查询出来，如果有变化还要校验
                Optional<CmdbCpuDetail> result = cmdbCpuDetailRepository.findById(cmdbCpuDetail.getCpuDetailId());
                if (result.isPresent()) {
                    if (result.get().getSn() != null && !result.get().getSn().equals(cmdbCpuDetail.getSn())) {
                        if (result.get().getIsDelete().equals(NO_DELETE)) {
                            findSame(cmdbCpuDetail,cmdbConfirm);
                        }
                    }
                    //修改情况存在未删除的记录
                } else {
                    findSame(cmdbCpuDetail,cmdbConfirm);
                }
            }

        }
    }

    public void findSame(CmdbCpuDetail cmdbCpuDetail,String cmdbConfirm) {
        List<CmdbCpuDetail> result = cmdbCpuDetailRepository.findAllBySnAndIsDelete(cmdbCpuDetail.getSn(), NO_DELETE);
        if (CollectionUtil.isNotEmpty(result)) {
            throw PlatformException.errorWithOutMail("序列号重复");
        }
        if (!StrUtil.equals(CMDB_CONFIRM,cmdbConfirm)){
            List<FlowFormPartIn> flowFormPartInDetails = flowFormPartInRepo.findFlowCpuSn(cmdbCpuDetail.getSn());
            if (CollectionUtil.isNotEmpty(flowFormPartInDetails)){
                throw PlatformException.errorWithOutMail("有发起过的流程"+flowFormPartInDetails.get(0).getProcessTitle()+"存在相同的cpu序列号");
            }
        }

    }

    public void deleteCpuDetail(CmdbCpuDetail cmdbCpuDetail, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(cmdbCpuDetail));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeId(cmdbCpuDetail.getCpuDetailId().toString());
        log.setChangeUser(account);
        log.setChangeType(DELETE_STRING);
        Optional<CmdbCpuDetail> optional = cmdbCpuDetailRepository.findById(cmdbCpuDetail.getCpuDetailId().intValue());
        if (optional.isPresent()) {
            CmdbCpuDetail bean = optional.get();
            bean.setIsDelete(DELETED);
            cmdbCpuDetailRepository.save(bean);
            cmdbChangeLogRepository.save(log);
        } else {
            throw PlatformException.errorWithOutMail("删除记录不存在");
        }
    }

    public void deleteByCodeList(List<String> codes, String account) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(codes));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeUser(account);
        log.setChangeType(DELETE_BATCH_STRING);
        cmdbChangeLogRepository.save(log);
        cmdbCpuDetailRepository.updateIsDeleteByCodes(DELETED, codes);
    }

    public void deleteByDeviceDetailId(Integer deviceDetailId, String operator) {
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(deviceDetailId));
        log.setChangeFrom(CMDB_DEVICE_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(DELETE_BATCH_STRING);
        cmdbChangeLogRepository.save(log);
        cmdbCpuDetailRepository.updateIsDeleteByDeviceDetailId(DELETED, deviceDetailId);
    }

    public void outByDeviceDetail(CmdbDeviceDetail h, String operator) {
        List<CmdbCpuDetail> cpuDetails = cmdbCpuDetailRepository.findAllByDeviceCodeAndIsDelete(h.getDeviceDetailCode(), NO_DELETED);
        cpuDetails.stream().forEach(e -> e.setLifeStatus(PART_LIFE_CYCLE_OUT));
        cmdbCpuDetailRepository.saveAll(cpuDetails);
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(h.getDeviceDetailId()));
        log.setChangeFrom(CMDB_DEVICE_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(UPDATE_STRING);
        cmdbChangeLogRepository.save(log);
    }

    public void outBySn(String sn, String operator) {
        List<CmdbCpuDetail> cpuDetails = cmdbCpuDetailRepository.findAllBySnAndIsDelete(sn, NO_DELETE);
        CmdbCpuDetail cpuDetail = cpuDetails.get(0);
        cpuDetail.setLifeStatus(PART_LIFE_CYCLE_OUT);
        cmdbCpuDetailRepository.save(cpuDetail);
        CmdbChangeLog log = new CmdbChangeLog();
        log.setChangeContent(JSONObject.toJSONString(sn));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeUser(operator);
        log.setChangeType(UPDATE_STRING);
        cmdbChangeLogRepository.save(log);
    }

    /**
     * 根据序列号查询
     * @param snList
     * @return
     */
    public List<CmdbCpuDetail> listBySn(List<String> snList) {
        Map<String, Object> param = new HashMap<>();
        param.put("INSTR_sn", StringUtils.join(snList,","));
        param.put("EQ_isDelete", 0);

        List<CmdbCpuDetail> detailLis = cmdbCpuDetailRepository.findAll(SpecificationUtil.buildSpecification(param, CmdbCpuDetail.class));
        return detailLis;
    }

    public List<CmdbCpuDetail> listByDetailCode(List<String> collect) {
        return cmdbCpuDetailRepository.findAllByCpuDetailCodeIn(collect);
    }
}
